//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at  http://www.nopCommerce.com/License.aspx. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations under the License.
// 
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
// 
// Contributor(s): _______. 
//------------------------------------------------------------------------------

using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using NopSolutions.NopCommerce.Common.Utils;


namespace NopSolutions.NopCommerce.Web.Administration.Modules
{
    public partial class WarningsControl : BaseNopAdministrationUserControl
    {
        private int CurrentTaskNo {
            get {
                return int.Parse(ViewState["CurrentTaskNo"] as string ?? "0");
            }
            set {
                ViewState["CurrentTaskNo"] = value.ToString();
            }
        }

        private Action[] _Tasks;

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            this._Tasks = new Action[] 
            {
                () => TestStoreUrl(),
                () => TestPrimaryExchangeRateCurrency(),
                () => TestPrimaryStoreCurrency(),
                () => TestBaseWeight(),
                () => TestBaseDimension(),
                () => TestMessageTemplates(),
                () => TestShippingMethods()
            };
        }

        protected void Page_Load(object sender, EventArgs e) {
            if (!Page.IsPostBack) {
                this.CurrentTaskNo = 0;
            }
        }

        private void MarkAsFail(Label label, Label resultLabel, string reason, string suggestion) {
            label.CssClass = "label label-warning";
            resultLabel.CssClass = "text-danger";
            label.Text += reason + suggestion;
        }

        private void MarkAsWarning(Label label, Label resultLabel, string suggestion) {
            label.CssClass = "label label-info";
            resultLabel.CssClass = "text-info";
            resultLabel.Text += suggestion;
        }

        private void MarkAsPass(Label label, Label resultLabel) {
            label.CssClass = "label label-success";
            resultLabel.Visible = false;
        }

        protected void RefreshTimer_Tick(object sender, EventArgs e) {
            this._Tasks[this.CurrentTaskNo]();

            this.CurrentTaskNo++;
            if (this.CurrentTaskNo == this._Tasks.Length) {
                this.RefreshTimer.Enabled = false;
            }
        }

        #region Tasks

        private void TestStoreUrl() {
            if (this.SettingManager.StoreUrl.Equals(CommonHelper.GetStoreLocation(false), StringComparison.InvariantCultureIgnoreCase)) {
                MarkAsPass(lblStoreUrl, lblStoreUrlResult);
            } else {
                MarkAsWarning(lblStoreUrl, lblStoreUrlResult, string.Format("Specified store URL ({0}) doesn't match this store URL ({1})", this.SettingManager.StoreUrl, CommonHelper.GetStoreLocation(false)));
            }
        }

        private void TestPrimaryExchangeRateCurrency() {
            if (this.CurrencyService.PrimaryExchangeRateCurrency != null) {
                MarkAsPass(lblPrimaryExchangeRateCurrency, lblPrimaryExchangeRateCurrencyResult);
            } else {
                MarkAsFail(lblPrimaryExchangeRateCurrency, lblPrimaryExchangeRateCurrency, "Primary exchange rate currency is not set", "<a href=\"Currencies.aspx\" class=\"btn\">Set it here</a>");
            }
        }

        private void TestPrimaryStoreCurrency() {
            if (this.CurrencyService.PrimaryStoreCurrency != null) {
                MarkAsPass(lblPrimaryStoreCurrency, lblPrimaryStoreCurrencyResult);
            } else {
                MarkAsFail(lblPrimaryStoreCurrency, lblPrimaryStoreCurrencyResult, "Primary store currency is not set", "<a href=\"Currencies.aspx\" class=\"btn\">Set it here</a>");
            }
        }

        private void TestBaseWeight() {
            if (this.MeasureService.BaseWeightIn != null) {
                MarkAsPass(lblDefaultWeight, lblDefaultWeightResult);
            } else {
                MarkAsFail(lblDefaultWeight, lblDefaultWeightResult, "Default weight is not set", "<a href=\"Measures.aspx\" class=\"btn\">Set it here</a>");
            }
        }

        private void TestBaseDimension() {
            if (this.MeasureService.BaseDimensionIn != null) {
                MarkAsPass(lblDefaultDimension, lblDefaultDimensionResult);
            } else {
                MarkAsFail(lblDefaultDimension, lblDefaultDimensionResult, "Default dimension is not set", "<a href=\"Measures.aspx\" class=\"btn\">Set it here</a>");
            }
        }

        private void TestMessageTemplates() {
            StringBuilder warningResult = new StringBuilder();
            var publishedLanguages = this.LanguageService.GetAllLanguages(false);
            warningResult.Append("<ul>");
            foreach (var messageTemplate in this.MessageService.GetAllMessageTemplates()) {
                foreach (var language in publishedLanguages) {
                    var localizedMessageTemplate = this.MessageService.GetLocalizedMessageTemplate(messageTemplate.Name, language.LanguageId);
                    if (localizedMessageTemplate == null) {

                        warningResult.AppendFormat("<li>You don't have localized version of \"{0}\" message template for {1}.</li>", messageTemplate.Name, language.Name);
                    }
                }
            }
            warningResult.Append("</ul>");

            string warnings = warningResult.ToString();
            if (String.IsNullOrEmpty(warnings)) {
                MarkAsPass(lblMessageTemplates, lblMessageTemplatesResult);
            } else {
                warningResult.Append("<a href=\"MessageTemplates.aspx\" class=\"btn\">Set it here</a>");
                warnings = warningResult.ToString();
                MarkAsWarning(lblMessageTemplates, lblMessageTemplatesResult, warnings);
            }
        }

        private void TestShippingMethods() {
            StringBuilder warningResult = new StringBuilder();
            var srcmList = this.ShippingService.GetAllShippingRateComputationMethods(false);
            int offlineSrcmCount = 0;
            foreach (var srcm in srcmList) {
                if (srcm.ShippingRateComputationMethodType == ShippingRateComputationMethodTypeEnum.Offline)
                    offlineSrcmCount++;
            }
            if (offlineSrcmCount > 1) {
                warningResult.Append("Only one offline shipping rate computation method is recommended to use");
            }
            string warnings = warningResult.ToString();
            if (String.IsNullOrEmpty(warnings)) {
                MarkAsPass(lblShippingMethods, lblShippingMethodsResult);
            } else {
                MarkAsWarning(lblShippingMethods, lblShippingMethodsResult, warnings);
            }
        }

        #endregion
    }
}